package com.s7.ui.arch;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import java.util.List;

/**
 * Fragment 基础类
 */
public abstract class ArchFragment extends Fragment {

    protected String LOG_TAG = this.getClass().getSimpleName();

    /**
     * 界面是否已创建完成
     */
    private boolean isViewCreated;

    /**
     * 是否对用户可见
     */
    private boolean isVisibleToUser;

    /**
     *  数据是否已请求, isNeedReload()返回 false 的时起作用
     */
    private boolean isDataLoaded = false;

    /**
     * 记录当前fragment的是否隐藏
     */
    private boolean isHidden = true;

    /**
     * 记录setUserVisibleHint方法是否tryLoadData成功，
     * 防止Fragment重新显示loadData被二次调用
     */
    private boolean isVisible = false;

    /**
     * onResume是否执行，避免和 onActivityCreated 重复调用  tryLoadData 方法
     */
    private boolean isResume = false;

    /**
     * 实现具体的数据请求逻辑
     */
    protected void loadData() {
    }

    /**
     * 使用ViewPager嵌套fragment时，切换ViewPager回调该方法
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        isResume = false;
        tryLoadData();
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        isResume = false;
        if (!isVisible) {
            tryLoadData();
        }
        isVisible = false;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isResume) {
            tryLoadData();
        }
        isResume = true;
    }

    /**
     * 使用show()、hide()控制fragment显示、隐藏时回调该方法
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isHidden = hidden;
        if (!hidden) {
            childLoadData();
        }
    }

    /**
     * ViewPager场景下，尝试请求数据
     */
    public void tryLoadData() {
        if (isObvious() && (isNeedReload() || !isDataLoaded)) {
            loadData();
            isDataLoaded = true;
            isVisible = true;
            dispatchParentVisibleState();
        }
    }

    /**
     * show()、hide()场景下，子类尝试请求数据
     */
    public void childLoadData() {
        if (!isParentHidden() && (isNeedReload() || !isDataLoaded)) {
            loadData();
            isDataLoaded = true;
            dispatchParentHiddenState();
        }
    }

    /**
     * ViewPager场景下，当前页面是否可见
     * @return
     */
    public boolean isObvious() {
        return isViewCreated && isVisibleToUser && isParentVisible();
    }

    /**
     * ViewPager场景下，判断父 fragment 是否可见
     * @return
     */
    public boolean isParentVisible() {
        Fragment fragment = getParentFragment();
        return fragment == null || (fragment instanceof ArchFragment
                && ((ArchFragment) fragment).isVisibleToUser);
    }

    /**
     * ViewPager场景下，当前fragment可见，如果其子fragment也可见，则尝试让子fragment加载请求
     */
    public void dispatchParentVisibleState() {
        FragmentManager fragmentManager = getChildFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        if (fragments.isEmpty()) {
            return;
        }
        for (Fragment child : fragments) {
            if (child instanceof ArchFragment && ((ArchFragment) child).isVisibleToUser) {
                ((ArchFragment) child).tryLoadData();
            }
        }
    }

    /**
     * fragment再次可见时，是否重新请求数据
     *   默认为 false (只请求一次数据)
     * @return
     */
    protected boolean isNeedReload() {
        return false;
    }

    /**
     * show()、hide()场景下
     * 当前fragment没隐藏，如果其子fragment也没隐藏，则尝试让子fragment请求数据
     */
    public void dispatchParentHiddenState() {
        FragmentManager fragmentManager = getChildFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        if (fragments.isEmpty()) {
            return;
        }
        for (Fragment child : fragments) {
            if (child instanceof ArchFragment && !((ArchFragment) child).isHidden) {
                ((ArchFragment) child).childLoadData();
            }
        }
    }

    /**
     * show()、hide()场景下，父fragment是否隐藏
     * @return
     */
    public boolean isParentHidden() {
        Fragment fragment = getParentFragment();
        if (fragment == null) {
            return false;
        } else if (fragment instanceof ArchFragment && !((ArchFragment) fragment).isHidden) {
            return false;
        }
        return true;
    }

    @Override
    public void onStop() {
        super.onStop();
        isVisible = false;
    }

    @Override
    public void onDestroy() {
        isViewCreated = false;
        isVisibleToUser = false;
        isDataLoaded = false;
        isHidden = true;
        super.onDestroy();
    }

    /**
     * 自定义 Activity 跳转间隔动画
     */
    public void onLoadingAnim() {

    }

    /**
     * 通过Class跳转界面
     **/
    protected void startActivity(Class<?> cls) {
        startActivity(cls, null);
    }
    /**
     * 含有Bundle通过Class跳转界面
     **/
    protected void startActivity(Class<?> cls, Bundle bundle) {
        onLoadingAnim();
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        if (bundle != null) {
            intent.putExtra("bundle", bundle);
        }
        startActivity(intent);
    }

    /**
     * 通过Class跳转界面
     * 关闭时获得该页面的返回参数
     **/
    protected void startActivity(Class<?> cls, int sign) {
        startActivity(cls, sign, null);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    protected void startActivity(Class<?> cls, int sign, Bundle bundle) {
        onLoadingAnim();
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        if (bundle != null) {
            intent.putExtra("bundle", bundle);
        }
        startActivityForResult(intent, sign);
    }

}
